package com.sms.dao.impl;

import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.criterion.DetachedCriteria;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.sms.dao.IBlackListDAO;
import com.sms.po.Blacklist;
/**
 * @author 20111006 by hzx
 */
public class BlackListDAO extends HibernateDaoSupport implements IBlackListDAO {
	private static final Log log = LogFactory.getLog(BlackListDAO.class);

	@SuppressWarnings("unchecked")
	@Override
	public List<Blacklist> showAllBlackList() {
		log.debug("finding all BlackList instances");
		try{
			return super.getHibernateTemplate().find("from Blacklist");
		}catch(RuntimeException e){
			log.debug("finding all failed:",e);
			throw e;
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Blacklist> showAllBlackListByPage(int start,int limit) {
		log.debug("finding all BlackList by pages");
		try{
			return super.getHibernateTemplate().findByCriteria(
					DetachedCriteria.forClass(Blacklist.class), start, limit);
		}catch(RuntimeException e){
			log.debug("finding all BlackList failed:",e);
			throw e;
		}
	}

	@Override
	public int getAllBlackListCount() {
		return this.showAllBlackList().size();
	}

	@Override
	public boolean addBlackList(Blacklist bl) {
		log.debug("add BlackList instance...");
		try{
			
			this.getHibernateTemplate().save(bl);
			return true;
		}catch(RuntimeException e){
			log.debug("add BlackList instance failed:",e);
			throw e;
		}
	}

	@Override
	public boolean removeBlackList(Blacklist bl) {
		log.debug("remove BlackList instance...");
		try{
			
			this.getHibernateTemplate().delete(bl);
			return true;
		}catch(RuntimeException e){
			log.debug("remove BlackList instance failed:",e);
			throw e;
		}
	}

	@Override
	public boolean updateBlackList(Blacklist bl) {
		log.debug("update BlackList instance...");
		try{
			this.getHibernateTemplate().update(bl);
			return true;
		}catch(RuntimeException e){
			log.debug("update BlackList instance failed:",e);
			throw e;
		}
	}
	
	public List<Blacklist> showUserBlackList(String userId) {
		log.debug("finding user and system BlackList instances");
		try{
			return super.getHibernateTemplate().find("from Blacklist where type=1 or (type=2 and user_Id='"+userId+"')");
		}catch(RuntimeException e){
			log.debug("finding all failed:",e);
			throw e;
		}
	}
	
	public boolean isBlacklist(String userId,String phone)
	{
		log.debug("finding user and system BlackList instances");
		try{
			List<Blacklist> blackList = super.getHibernateTemplate().find("from Blacklist where (type=1 or (type=2 and user_Id='"+userId+"')) and phone='"+phone+"'");
			return !blackList.isEmpty();
		}catch(RuntimeException e){
			log.debug("finding all failed:",e);
			throw e;
		}
	}

}
